// pages/memberDetail/memberDetail.js
var config = require("../../config.js")
var util = require("../../utils/MD5.js")
var com = require('../../utils/common.js');
var req = require("../../utils/reqGet.js");
var timer = null;
/**
 * 记录
 * 重置密码，先获取操作人员信息
 * TODO...
 */
Page({

  /**
   * 页面的初始数据
   */
  data: {
    options: {
      mebno: "116803"
    },
    ShopNo: "", // 店铺编号
    MebNo: "",
    delay: 0,
    member: {},
    showDialog: false,
    dialogType: 7,
    rechargeAmount: "",
    rechargeSendAmount: "",
    rechargeSendScore: "",
    resetPassword: "", // 重置密码
    opInfo: "",
    memberCard: "",
    newTel: "",
    years: [],
    months: [],
    days: [],
    delayDate: "",
    fullMounths: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    currentMonths: [],
    currentDays: [],
    showDateChoose: false, // 是否展开日期选择
    alterPric: 0,
    payPrice: 0,
    MebId: "",
    payType: 1,
    payPic: "",
    showEwm: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 19811
    this.data.options = options;
    // this.data.options = { mebno: "116756" };
    wx.getStorage({
      key: 'OP_INFO',
      success: res => {
        this.data.opInfo = res.data;
      },
    })
  },

  /**
   * 获取会员详情
   */
  getMemberDetail() {
    var str = `ShopNo&MebNo=${this.data.shopNo}*${this.data.MebNo}`;
    var md5 = util.md5(str);
    var data = {
      bNo: "1207",
      ShopNo: this.data.shopNo,
      MebId: this.data.MebId,
      MD5: md5.toUpperCase(),
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        // 如果请求成功并且有结果
        if (res.data.code === "100" && res.data.Result.length > 0) {
          if (res.data.Result[0].C_MB_PIC) {
            res.data.Result[0].C_MB_PIC = config.FilePath + res.data.Result[0].C_MB_PIC
          } else {
            res.data.Result[0].C_MB_PIC = "/images/d-face.jpg";
          }

          switch (res.data.Result[0].C_MB_SEX) {
            case 1:
              res.data.Result[0].C_MB_SEX = "男";
              break;
            case 2:
              res.data.Result[0].C_MB_SEX = "女";
              break;
            case 3:
              res.data.Result[0].C_MB_SEX = "保密";
              break;
          }

          this.setData({
            delay: res.data.Result[0].D_DUT_TIME == "永不过期" ? 1 : 0,
          })

          if (res.data.Result[0].D_DUT_TIME == "永不过期") {
            res.data.Result[0].D_DUT_TIME = "0001-01-01"
          }

          this.setData({
            delayDate: res.data.Result[0].D_DUT_TIME != "永不过期" ? res.data.Result[0].D_DUT_TIME : "0001-01-01",
            member: res.data.Result[0]
          })

          this.setDatePickerData()
        } else {
          wx.showModal({
            title: '提示',
            content: '会员信息异常，获取会员信息失败',
            showCancel: false,
          })
        }
      }
    })
  },
    // 跳转修改积分
    integralChange() {
        wx.navigateTo({
            url: '/pages/memberDetail/integralChange/integralChange',
        })
    },

  showRechargeOptions() {
    if (!this.data.rechargeAmount) {
      wx.showModal({
        title: '提示',
        content: '请填写充值金额',
        showCancel: false,
      })
      return;
    }
    wx.showActionSheet({
      itemList: ["现金", "支付宝支付", "微信支付"],
      success: res => {
        this.data.payType = res.tapIndex + 1;
        this.recharge();
      }
    })
  },

  clearScore() {
    wx.showModal({
      title: '提示',
      content: '确定把会员积分清零',
      success: res => {
        if (res.confirm) {
          req({
            bNo: 1218,
            MebNo: this.data.member.C_MB_NO,
            opname: this.data.opInfo.c_name,
            opid: this.data.opInfo.n_ss_id
          }, (data) => {
            if (data.Result == 1) {
              wx.showToast({
                title: '已清零',
                duration: 1000
              })
              this.getMemberDetail()
            } else {
              wx.showModal({
                title: '提示',
                content: '操作失败，请重试',
                showCancel: false,
              })
            }
          })
        }
      }
    })
  },

  setDatePickerData() {
    if (!this.data.member.C_MB_NO) {
      return;
    }
    var d = "";
    if (this.data.member.D_DUT_TIME != "0001-01-01") {
      d = this.data.member.D_DUT_TIME.split("-");
    } else {
      var date = new Date();
      d = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
    }
    var y = [];
    var m = [];
    var days = [];
    for (var i = 0; i < 30; i++) {
      y.push(parseInt(d[0]) + i);
    }

    for (var i = parseInt(d[1]); i < 13; i++) {
      m.push(i);
    }

    for (var i = parseInt(d[2]); i <= this.filterDate(d[0], parseInt(d[1])); i++) {
      days.push(i);
    }

    this.setData({
      years: y,
      months: m,
      currentMonths: m,
      currentDays: days,
      days,
    })
  },

  chooseDate() {
    this.setData({
      showDateChoose: true,
    })
  },

  edit(ev) {
    wx.removeStorage({
      key: 'member_data',
    })

    wx.removeStorage({
      key: 'choose_member_tag',
      success: function(res) {
        wx.setStorage({
          key: "member_data",
          data: ev.currentTarget.dataset.d,
        })
        wx.navigateTo({
            url: '/pages/editMember/editMember?MebId=' + ev.currentTarget.dataset.d.N_MB_ID + '&edit=true',
        })
      },
    })
  },

  hideDateChoose() {
    this.setData({
      showDateChoose: false,
    })
  },

  filterDate(year, month) {
    var d = 0;
    if (/^(1|3|5|7|8|10|12)$/.test(month)) {
      d = 31;
    } else if (/^(4|6|9|11)$/.test(month)) {
      d = 30;
    } else if (/^2$/.test(month)) {
      if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
        d = 29;
      } else {
        d = 28;
      }
    } else {
      throw new Error('month is illegal');
    }
    return d;
  },

  bindChange(ev) {
    var year = new Date().getFullYear();
    var date = "";
    if (year == this.data.years[ev.detail.value[0]]) {
      this.setData({
        months: this.data.currentMonths,
        days: this.data.currentDays,
      })
    } else {
      var days = [];
      for (var i = 1; i <= this.filterDate(this.data.years[ev.detail.value[0]], parseInt(this.data.months[ev.detail.value[1]])); i++) {
        days.push(i);
      }
      this.setData({
        months: this.data.fullMounths,
        days,
      })
    };

    if (this.data.months[ev.detail.value[1]] < 10) {
      this.data.months[ev.detail.value[1]] = "0" + this.data.months[ev.detail.value[1]];
    }

    if (this.data.days[ev.detail.value[2]] < 10) {
      this.data.days[ev.detail.value[2]] = "0" + this.data.days[ev.detail.value[2]];
    }

    this.setData({
      delay: 0,
      delayDate: `${this.data.years[ev.detail.value[0]]}-${this.data.months[ev.detail.value[1]]}-${this.data.days[ev.detail.value[2]]}`,
    })
  },

  setMebNo() {
    this.data.MebNo = this.data.options.mebno;
    this.data.MebId = this.data.options.id;
    // this.data.MebId = 19811;
    // 19811
    this.getMemberDetail();
  },

  /**
   * 充值方式
   * 现金或者微信收款
   * 微信收款只能展示收款码让用户扫码后支付
   */
  recharge() {
    wx.showLoading({
      title: '',
    })
    var _this = this;
    
    com.recharge(this.data.rechargeAmount, this.data.rechargeSendAmount, this.data.rechargeSendScore, this.data.shopNo, this.data.member.C_MB_NO, (res) => {
      if (this.data.payType == 1) {
        // 现金充值
        this.regCash(res.orderNO);
      } else if (this.data.payType == 2) {
        this.getPayEwm(3, res.orderNO)
      } else if (this.data.payType == 3) {
        this.getPayEwm(1, res.orderNO)
      }
    })
  },

  regCash(order) {
    var str = `orderNo&payWay&zfls&payAmount=${order}*11**${this.data.rechargeAmount}`;
    var md5 = util.md5(str);
    var reqData = {
      bNo: 412,
      orderNo: order,
      payWay: 11,
      zfls: "",
      payAmount: this.data.rechargeAmount,
      MD5: md5.toUpperCase()
    };

    wx.request({
      url: config.requestUrl,
      data: reqData,
      success: res => {
        var data2 = JSON.parse(res.data.replace(/\(|\)/g, ""));

        if (data2.code === "100") {
          wx.showToast({
            title: '充值成功',
            duration: 1000,
          });
          this.setData({
            showDialog: false
          })
          this.getMemberDetail();
        } else {
          wx.showToast({
            title: '充值失败',
            duration: 1000,
            icon: 'none'
          })
        }

        wx.hideLoading()
      }
    })
  },

  getPayEwm(type, orderNO) {
    req({
      bNo: 3206,
      PayAmount: this.data.rechargeAmount,
      PayWay: type,
      ShopNo: this.data.shopNo,
      OrderNo: orderNO
    }, (data) => {
      wx.hideLoading();
      if (data.imgurl) {
        this.setData({
          showEwm: true,
          payPic: data.imgurl,
        })
        this.checkPayResult(orderNO, data.CxONo, type)
      } else {
        wx.showModal({
          title: '提示',
          content: data.Result,
          showCancel: false,
        })
      };
    })
  },

  checkPayResult(orderNo, CxONo, type) {
    timer = setInterval(() => {
      req({
        bNo: 3207,
        OrderNo: orderNo,
        CxONo,
        PayAmount: this.data.rechargeAmount,
        PayWay: type,
        opid: this.data.opInfo.n_ss_id,
      }, (data) => {
        if (data.Result == "支付完成") {
          clearInterval(timer);
          this.getMemberDetail();
          wx.showToast({
            title: '充值成功',
            duration: 1000,
            success: res => {
              setTimeout(() => {
                this.setData({
                  showDialog: false,
                  showEwm: false
                })
              })
            }
          })
        }
      })
    }, 2000);
  },

  hideEwmDialog() {
    wx.showModal({
      title: '提示',
      content: '确认放弃收款吗？',
      success: res => {
        if (res.confirm) {
          this.setData({
            showDialog: false,
            showEwm: false
          })
          clearInterval(timer);
        }
      }
    })
  },

  /**
   * 显示充值弹窗
   */
  showRchargeDialog() {
    this.setData({
      showDialog: true,
      dialogType: 1,
    })
    this.getAfterPrice();
  },

  /**
   * 展示重置密码窗口
   */
  showResetDialog() {
    this.setData({
      showDialog: true,
      dialogType: 2,
    })
  },

  /**
   * 展示清卡窗口
   */
  showClearDialog() {
    this.setData({
      showDialog: true,
      dialogType: 3,
    })
  },

  /**
   * 展示挂失窗口
   */
  showReportDialog() {
    this.setData({
      showDialog: true,
      dialogType: 4,
    })
  },

  /**
   * 展示锁卡窗口
   */
  showLockDialog() {
    this.setData({
      showDialog: true,
      dialogType: 5,
    })
  },

  /**
   * 展示补卡窗口
   */
  showIssueDialog() {
    this.setData({
      showDialog: true,
      dialogType: 6,
    })
  },

  /**
   * 展示延期窗口
   */
  showDelayDialog() {
    this.setData({
      showDialog: true,
      dialogType: 7,
    })
  },

  /**
   * 设置是否永久不过期
   */
  setDelayAllow() {
    this.setData({
      delay: this.data.delay == 1 ? 0 : 1,
      delayDate: "0001-01-01",
    })
  },

  /**
   * 设置充值金额
   */
  setRechargeAmount(ev) {
    this.setData({
      rechargeAmount: this.filterAmount(ev.detail.value)
    })

    this.getAfterPrice();
  },

  /**
   * 筛选金额
   */
  filterAmount(str) {
    str = str.replace(/[^\d^\.]/g, "");
    if (str.indexOf(".") != -1) {
      if (str.indexOf(".") == 0) {
        str += "0." + str;
      }
      return str.match(/\d+\.\d{0,2}/g)[0]
    } else {
      return parseInt(str);
    }
  },

  /**
   * 设置充值时赠送金额
   */
  setSendAmount(ev) {
    this.setData({
      rechargeSendAmount: this.filterAmount(ev.detail.value)
    })
    this.getAfterPrice();
  },

  getAfterPrice() {
    var rechargeAmount = this.data.rechargeAmount ? this.data.rechargeAmount : 0;
    var rechargeSendAmount = this.data.rechargeSendAmount ? this.data.rechargeSendAmount : 0;
    var price = parseFloat(this.data.member.N_MB_AMOUNT) + parseFloat(rechargeAmount) + parseFloat(rechargeSendAmount);
    // var payPrice = rechargeAmount + rechargeSendAmount;
    this.setData({
      alterPric: price.toFixed(2),
      // payPrice,
    })
  },

  /**
   * 设置充值时赠送积分
   */
  setSendScore(ev) {
    this.setData({
      rechargeSendScore: ev.detail.value.replace(/[^\d]/g, "") * 1,
    })
  },

  /**
   * 设置重置的密码
   */
  setResetPassword(ev) {
    this.data.resetPassword = ev.detail.value;
  },

  /**
   * 设置会员卡号
   */
  setMemberCard(ev) {
    this.data.memberCard = ev.detail.value;
  },

  /**
   * 设置会员电话
   */
  setMemberTel(ev) {
    this.data.newTel = ev.detail.value;
  },

  /**
   * 隐藏窗口
   */
  closeDialog() {
    this.setData({
      showDialog: false,
    })
  },

  /**
   * 重置密码操作
   */
  setPasswrod() {

    if (this.data.resetPassword.length < 6) {
      wx.showModal({
        title: '提示',
        content: '请设置长度为6位及其以上的密码',
        showCancel: false
      })

      return;
    }
    wx.showLoading({
      title: '',
      mask: true
    })
    com.resetPassword({
      bNo: 1211,
      MebNo: this.data.member.C_MB_NO,
      ShopNo: this.data.shopNo,
      opname: this.data.opInfo.c_name,
      pwd: this.data.resetPassword,
      opid: this.data.opInfo.n_ss_id,
    }, () => {
      this.closeDialog();
      wx.showToast({
        title: '重置成功',
        duration: 1000,
        mask: true,
      })
      wx.hideLoading()
    })
  },

  /**
   * 清卡操作
   */
  clearCard() {
    wx.showLoading({
      title: '',
      mask: true
    })
    com.clearCard({
      bNo: 1212,
      MebNo: this.data.member.C_MB_NO,
      ShopNo: this.data.shopNo,
      opname: this.data.opInfo.c_name,
      opid: this.data.opInfo.n_ss_id,
    }, () => {
      this.closeDialog();
      wx.showToast({
        title: '已清卡',
        duration: 1000,
        mask: true,
        success: res => {
          wx.hideLoading()
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          })
        }
      })

    })
  },

  del() {
    wx.showLoading({
      title: '',
      mask: true
    })
    com.delMember({
      bNo: 1219,
      mebid: this.data.member.N_MB_ID,
      ShopNo: this.data.shopNo,
      mebName: this.data.member.C_MG_NAME,
      opname: this.data.opInfo.c_name,
      opid: this.data.opInfo.n_ss_id,
    }, () => {
      this.closeDialog();
      wx.showToast({
        title: '已删除',
        duration: 1000,
        mask: true,
        success: res => {
          wx.hideLoading()
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000)
        }
      })
    })
  },

  /**
   * 挂失操作
   */
  lossReprot() {
    var state = 2;
    if (this.data.member.N_CARD_STATE == "挂失") {
      state = 1
    }
    wx.showLoading({
      title: '',
      mask: true
    })
    com.lossReport({
      bNo: 1213,
      ShopNo: this.data.shopNo,
      MebNo: this.data.member.C_MB_NO,
      opname: this.data.opInfo.c_name,
      opid: this.data.opInfo.n_ss_id,
      state
    }, () => {
      this.closeDialog();
      var title = "已挂失";
      if (this.data.member.N_CARD_STATE == "挂失") {
        title = "已解挂"
      }
      wx.showToast({
        title,
        duration: 1000,
        mask: true,
        success: res => {
          setTimeout(() => {
            this.getMemberDetail();
          })
        }
      })

      wx.hideLoading()
    })
  },

  /**
   * 锁卡操作
   */
  lockCard() {
    var state = 5;
    if (this.data.member.N_CARD_STATE == "锁定") {
      state = 1
    }

    wx.showLoading({
      title: '',
      mask: true
    })
    com.lossReport({
      bNo: 1213,
      ShopNo: this.data.shopNo,
      MebNo: this.data.member.C_MB_NO,
      opname: this.data.opInfo.c_name,
      opid: this.data.opInfo.n_ss_id,
      state,
    }, () => {
      this.closeDialog();
      var title = "已锁定";
      if (this.data.member.N_CARD_STATE == "锁定") {
        title = "已解锁"
      }
      wx.showToast({
        title,
        duration: 1000,
        mask: true,
        success: res => {
          this.getMemberDetail();
        }
      })
      wx.hideLoading()
    })
  },

  /**
   * 补卡操作
   */
  issueCard() {
    // 如果没有新的手机号
    // 就使用原本的手机号作为补卡手机号
    var newTel = this.data.member.C_MB_PHONE;
    // 如果有设置新的手机号则使用新手机号
    if (/1\d{10}/.test(this.data.newTel)) {
      newTel = this.data.newTel;
    }

    if (!this.data.memberCard) {
      wx.showModal({
        title: '提示',
        content: '请填写或者生成新卡号',
        showCancel: false,
      })

      return;
    }
    wx.showLoading({
      title: '',
      mask: true
    })
    com.issueCard({
      bNo: 1214,
      MebNo: this.data.member.C_MB_NO,
      ShopNo: this.data.shopNo,
      cardNo: this.data.memberCard,
      phone: newTel,
      oldphone: this.data.member.C_MB_PHONE,
      opname: this.data.opInfo.c_name,
      opid: this.data.opInfo.n_ss_id,
    }, () => {
      this.closeDialog();
      wx.showToast({
        title: "补卡成功",
        duration: 1000,
        mask: true,
        success: res => {
          this.getMemberDetail();
        }
      })
      wx.hideLoading()
    })
  },

  /**
   * 发送优惠券
   */
  sendCoupon() {
    wx.navigateTo({
      url: '/pages/sendCoupon/sendCoupon',
    })
  },

  memberDelay() {
    wx.showLoading({
      title: '',
      mask: true
    })
    com.memberDelay({
      bNo: 1215,
      MebNo: this.data.member.C_MB_NO,
      opname: this.data.opInfo.c_name,
      ShopNo: this.data.shopNo,
      opid: this.data.opInfo.n_ss_id,
      currentTime: this.data.member.D_DUT_TIME,
      endTime: this.data.delayDate,
      isybgq: this.data.delay
    }, () => {
      this.closeDialog();
      wx.showToast({
        title: "延期成功",
        duration: 1000,
        mask: true,
        success: res => {
          wx.hideLoading()
          wx.navigateBack({
            delta: 1,
          })
        }
      })
    })
  },

  createCard() {
    com.createCard({
      bNo: 1216,
      ShopNo: this.data.shopNo,
    }, res => {
      this.setData({
        memberCard: res.split(",")[0]
      })
    })
  },

  /**
   * 预览用户选择的图片
   */
  previewImage(src) {
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: [src] // 需要预览的图片http链接列表
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.getStorage({
      key: 'C_SHOP_NO',
      success: res => {
        this.data.shopNo = res.data;
        this.setMebNo();
      },
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
})